﻿using AutoMapper;
using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Model.Store;
using SIG.Service;
using SIG.ViewModel.Front.Store;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SIG.WebMVC.Controllers
{
    public class GoodsController : Controller
    {
        // GET: Goods
        private readonly IGoodsCategoryService _goodsCategoryService;
        private readonly IGoodsService _goodsService;
        private readonly IPageMetaService _pageMetaService;
        private IMapper _mapper;
        public GoodsController(IGoodsService goodsService, IGoodsCategoryService goodsCategoryService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _goodsService = goodsService;
            _goodsCategoryService = goodsCategoryService;
            _pageMetaService = pageMetaService;
            _mapper = mapper;
        }

        // GET: Admin/Pages
        [SIGActionFilter]
        public ActionResult Index(int? page, int? categoryId, string keyword)
        {
            var goodsListVM = new GoodsListVM();

            if (categoryId != null)
                goodsListVM.CategoryId = (int)categoryId;

            goodsListVM.Keyword = keyword;
            goodsListVM.PageIndex = (page ?? 1) - 1;
            goodsListVM.PageSize = SettingsManager.Store.PageSize;
            int totalCount;
            var goodslist = _goodsService.GetPagedActiveElements(goodsListVM.PageIndex, goodsListVM.PageSize, goodsListVM.Keyword, goodsListVM.CategoryId, out totalCount);
            var categoryVMList = _mapper.Map<List<Goods>, List<GoodsVM>>(goodslist);
            goodsListVM.TotalCount = totalCount;

            goodsListVM.Goods = new StaticPagedList<GoodsVM>(categoryVMList, goodsListVM.PageIndex + 1, goodsListVM.PageSize, goodsListVM.TotalCount); ;

            var categoryList = _goodsCategoryService.GetAll().OrderByDescending(c => c.Importance).ToList();
            var categories = new SelectList(categoryList, "Id", "Title");
            ViewBag.Categories = categories;

            return View(goodsListVM);           

        }

        public PartialViewResult FeaturedGoods()
        {
            var list = _goodsService.LatesterGoods(4);
            var goodsList = _mapper.Map<IEnumerable<Goods>, IEnumerable<GoodsVM>>(list);
            return PartialView("_FeaturedGoods", goodsList);
        }
    }
}